import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query, Req } from '@nestjs/common';
import { AddDto, PageDto, UpdateDto } from './dto';
import { PricingRuleService } from './pricing-rule.service';
import { BaseController } from '../base/base.controller';
import { DtoPipe } from '../pipes/dto/dto.pipe';

@Controller('pricingRule')
export class PricingRuleController extends BaseController{
    constructor(
        private readonly service:PricingRuleService
    ){
        super()
    }

    @Get('options')
    async options(@Query('type', ParseIntPipe) type:number, @Req() { userId }) {
        const result = type == 1 ? (await this.service.optionsOfFast(userId)) : (await this.service.optionsOfSlow(userId))
        return this.successRes(result)
    }

    @Get('page')
    async rolePage(@Query() dto:PageDto, @Req() { userId }) {
        const result = Number(dto.type) == 1 ? (await this.service.fastPage(userId, dto.pageNo || 1, dto.pageSize || 20, dto.name)) : (await this.service.slowPage(userId, dto.pageNo || 1, dto.pageSize || 20, dto.name))
        return this.successRes(result)
    }

    @Post('add')
    async add(@Query('type', ParseIntPipe) type:number, @Body(new DtoPipe({skipMissingProperties : false})) dto:AddDto, @Req() { userId }) {
        const result = type == 1 ? (await this.service.addFast(dto.name || '', dto.rules || [], dto.pay || '0', userId, this.utils.time())) : (await this.service.addSlow(dto.name || '0', dto.price || '0', dto.service || '0', dto.hourKwh || 0, userId, this.utils.time()))
        return this.successRes(result)
    }

    @Put('update/:type/:id')
    async update(@Param('type', ParseIntPipe) type:number, @Param('id', ParseIntPipe) id:number, @Body(new DtoPipe({skipMissingProperties : true})) dto:UpdateDto, @Req() { userId }) {
        const result = type == 1 ? (await this.service.updateFast(id, dto, userId, this.utils.time())) : (await this.service.updateSlow(id, dto, userId, this.utils.time()))
        return this.successRes(result)
    }

    @Delete('del/:type/:id')
    async del(@Param('type', ParseIntPipe) type:number, @Param('id', ParseIntPipe) id:number, @Req() { userId }) {
        const result = type == 1 ? (await this.service.delFast(id, userId)) : (await this.service.delSlow(id, userId))
        return result ? this.successRes() : this.failRes()
    }
}
